package com.lanhao.aot.spider;

import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;

public class NetSpiderFor17Track {
	public static final String trackUrl = "https://t.17track.net/restapi/track";

	public static void main(String[] args) {

//		String data= "{\"data\":[{\"num\":\"PQ5J0A0710032970128947X\",\"fc\":\"0\",\"sc\":\"0\"}],\"guid\":\"\",\"timeZoneOffset\":-480}";
//		
//		String result = HttpUtil.post(trackUrl, data);
//		
//		System.out.println("调用结果result=" + result);

		String data = "{\"guid\":\"\",\"data\":[{\"num\":\"PQ5J0A0710032970128947X\"}],\"timeZoneOffset\":-480}";

		try {
			String jsName = "17track";
			// 创建一个脚本引擎管理器
			ScriptEngineManager manager = new ScriptEngineManager();
			// 获取一个指定的名称的脚本引擎
			ScriptEngine engine = manager.getEngineByName("js");
			// 获取js文件所在目录的路径
//			String path = NetSpiderFor17Track.class.getResource("").getPath()+"/js/";
			String path = "D:/";
			engine.eval(new FileReader(path + jsName + ".js"));
			// 3.将引擎转换为Invocable，这样才可以掉用js的方法
			Invocable invocable = (Invocable) engine;
			// 4.使用 invocable.invokeFunction掉用js脚本里的方法，第一個参数为方法名，后面的参数为被调用的js方法的入参
			String guId = (String) invocable.invokeFunction("get_cookie", data);
			System.out.println("=======guId========" + guId);
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("data", data);
			String trackResult = HttpRequest.post(trackUrl)
					.header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36") // 头信息，多个头信息多次调用此方法即可
					.header(Header.COOKIE, "Last-Event-ID=" + guId)
			    	.form(paramMap) //表单内容
//					.body(data)
					.timeout(20000)// 超时，毫秒
					.execute().body();
			System.out.println("=======trackResult========" + trackResult);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
